//
//  MineDrawerController.m
//  Mine
//
//  Created by CPX on 2018/8/28.
//  Copyright © 2018年 CPX. All rights reserved.
//

#import "MineDrawerController.h"
#import "MineTool.h"
#import "LoginController.h"
#import "SignupViewController.h"
#import "MineProfileController.h"

/**
 我的侧滑
 @author yzl
 */
@interface MineDrawerController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *table;
@property (nonatomic,strong) UIButton *portraitView;
@property (nonatomic,strong) UILabel *nicknameLabel;

@property (nonatomic,strong) UIButton *loginBtn;
@property (nonatomic,strong) UIButton *signupBtn;

@property (nonatomic,strong) NSMutableArray *data;


@end

@implementation MineDrawerController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [self initUI];
    [self loadData];
}

- (void)initUI{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, .83*kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    UIEdgeInsets e = self.table.contentInset;
    self.table.separatorStyle = UITableViewCellSelectionStyleNone;
    e.top = - 20;
    self.table.contentInset = e;
    [self.view addSubview:self.table];
    
    self.table.delegate = self;
    self.table.dataSource = self;
    
    UIView *tbH = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth*0.83, 164)];
    tbH.backgroundColor = UIColorHex(#F3F5F4);
    self.portraitView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 74, 74)];
    [self.portraitView addTarget:self action:@selector(onPortraitViewTouched) forControlEvents:UIControlEventTouchUpInside];
    self.portraitView.layer.cornerRadius = 37;
    self.portraitView.layer.masksToBounds = YES;
    self.portraitView.centerX = tbH.width/2;
    self.portraitView.bottom = tbH.height - 44;
    [tbH addSubview:self.portraitView];
    
    self.nicknameLabel = [UILabel new];
    self.nicknameLabel.text = @"Text";
    self.nicknameLabel.textColor = UIColorHex(#000A05);
    self.nicknameLabel.textAlignment = NSTextAlignmentCenter;
    self.nicknameLabel.width = tbH.width - 30;
    self.nicknameLabel.centerX = self.portraitView.centerX;
    self.nicknameLabel.top = self.portraitView.bottom + 6;
    self.nicknameLabel.height = 22.5;
    self.nicknameLabel.font = [UIFont systemFontOfSize:12];
    [tbH addSubview:self.nicknameLabel];
    
    self.signupBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.signupBtn.frame = CGRectMake(0, 0, 115, 44);
    [self.signupBtn addTarget:self action:@selector(onSignupTouched) forControlEvents:UIControlEventTouchUpInside];
    self.signupBtn.backgroundColor = [UIColor whiteColor];
    [self.signupBtn setTitle:TLString(@"sign_up") forState:UIControlStateNormal];
    self.signupBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [self.signupBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.signupBtn.layer.masksToBounds = YES;
    self.signupBtn.layer.cornerRadius = 22;
    self.signupBtn.layer.borderColor = UIColorHex(#D6D6D6).CGColor;
    self.signupBtn.layer.borderWidth = .5f;
    [tbH addSubview:self.signupBtn];
    self.signupBtn.bottom = tbH.height - 47;
    self.signupBtn.right = tbH.width/2-13;
    
    self.loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginBtn.frame = CGRectMake(0, 0, 115, 44);
    [self.loginBtn addTarget:self action:@selector(onLoginTouched) forControlEvents:UIControlEventTouchUpInside];
    [self.loginBtn setTitle:TLString(@"LOGIN") forState:UIControlStateNormal];
    self.loginBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    self.loginBtn.backgroundColor = UIColorHex(#2B9958);
    [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.layer.cornerRadius = 22;
    [tbH addSubview:self.self.loginBtn];
    self.loginBtn.bottom = tbH.height - 47;
    self.loginBtn.left = tbH.width/2+13;
    
    self.portraitView.hidden = YES;
    self.nicknameLabel.hidden = YES;
    self.table.tableHeaderView = tbH;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.33 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
    });

    if ([MineTool sharedTool].isLogin) {
        self.loginBtn.hidden = YES;
        self.signupBtn.hidden = YES;
        self.portraitView.hidden = NO;
        [self.portraitView sd_setImageWithURL:[NSURL URLWithString:[MineTool sharedTool].avatar] forState:UIControlStateNormal placeholderImage:[UIImage RTL_ImageWithName:@"no_photo"]];
        self.nicknameLabel.hidden= NO;
        self.nicknameLabel.text = [MineTool sharedTool].username;
    }
    else{
        self.portraitView.hidden = YES;
        self.nicknameLabel.hidden= YES;
        self.loginBtn.hidden = NO;
        self.signupBtn.hidden = NO;
    }
}

- (void)loadData{
    WeakSelf
    
    SettingsPushModel *item6 = [SettingsPushModel new];
    
    item6.title = TLString(@"social_my_wish");
    item6.targetClass = NSClassFromString(@"MyAzkarViewController");
    
    SettingsPushModel *item7 = [SettingsPushModel new];
    NSArray *options = @[TLString(@"Standard(Shafi,Maliki,Hanbali)"),TLString(@"Hanafi")];
    item7.title = TLString(@"Asr Calculation - Juristic Method");
    item7.subTitle = options[[MineTool sharedTool].asr];
    item7.block = ^{
        [FIRAnalytics logEventWithName:@"click_asr" parameters:nil];
        [weakSelf showAsrOptions];
    };
    
    SettingsPushModel *item8 = [SettingsPushModel new];
    options = @[TLString(@"Angle-based method"),TLString(@"Middle of the night"),TLString(@"1/7 of the night")];
    item8.title = TLString(@"High Latitude Adjustment");
    item8.subTitle =  options[[MineTool sharedTool].highLatitude-1];
    item8.block = ^{
        [FIRAnalytics logEventWithName:@"click_high" parameters:nil];
        [weakSelf showHighLatitudeOptions];
    };
    
    SettingsPushModel *item81 = [SettingsPushModel new];
    options = @[TLString(@"Jafari"),TLString(@"Karachi"),TLString(@"ISNA"),TLString(@"MWL"),TLString(@"Makkah"),TLString(@"Egypt"),TLString(@"Tehran")];
    item81.title = TLString(@"Calculation_Methods");
    item81.subTitle = options[[MineTool sharedTool].prayTimeCalMeth];;
    item81.block = ^{
        [FIRAnalytics logEventWithName:@"click_high" parameters:nil];
        [weakSelf showPrayTimeCalOptions];
    };
    
    NSMutableArray *c = [NSMutableArray arrayWithObjects:item7,item8,item81, nil];
    if ([MineTool sharedTool].isLogin) {
//        [c insertObject:item6 atIndex:0];
    }
    
    SettingsPushModel *item9 = [SettingsPushModel new];
    item9.title = TLString(@"ShareApp");
    item9.block = ^{
        [FIRAnalytics logEventWithName:@"click_share" parameters:nil];
        [weakSelf shareApp];
    };
    
    SettingsPushModel *item10 = [SettingsPushModel new];
    item10.title = TLString(@"Feedback");
    item10.targetClass = NSClassFromString(@"FeedbackController");
    
    SettingsPushModel *item11 = [SettingsPushModel new];
    item11.title = TLString(@"Aboutus");
    item11.targetClass = NSClassFromString(@"AboutUsController");
    
    NSMutableArray *d = [NSMutableArray arrayWithObjects:item9,item10,item11, nil];
    
    self.data = [NSMutableArray array];
    [self.data addObjectsFromArray:@[c,d]];
    
    [self.table reloadData];
}

- (void)showAsrOptions{
    NSArray *options = @[TLString(@"Standard(Shafi,Maliki,Hanbali)"),TLString(@"Hanafi")];
    MyAlertOptionViewV3 *alert = [MyAlertOptionViewV3 viewWithOptions:options selectIdx:[MineTool sharedTool].asr];
    [alert addActionWithTitle:TLString(@"Cancel") color:UIColorHex(#334139)];
    [alert addActionWithTitle:TLString(@"Done") color:UIColorHex(#00732F)];
    
    alert.block = ^(NSInteger btnIdx,NSInteger selectedIdx) {
        if (btnIdx == 1) {
            SettingsPushModel *item7 = self.data[0][0];
            item7.subTitle = options[selectedIdx];
            if ([MineTool sharedTool].asr != selectedIdx) {
                [[MineTool sharedTool] saveAsr:selectedIdx];
                [self.table reloadData];
                [[NSNotificationCenter defaultCenter] postNotificationName:PrayTimeAlgorithmChangedNotification object:nil];
            }
        }
    };
    [alert show:NO];
}

- (void)showHighLatitudeOptions{
    NSArray *options = @[TLString(@"Angle-based method"),TLString(@"Middle of the night"),TLString(@"1/7 of the night")];
    MyAlertOptionViewV3 *alert = [MyAlertOptionViewV3 viewWithOptions:options selectIdx:[MineTool sharedTool].highLatitude-1];
    [alert addActionWithTitle:TLString(@"Cancel") color:UIColorHex(#334139)];
    [alert addActionWithTitle:TLString(@"Done") color:UIColorHex(#00732F)];
    
    alert.block = ^(NSInteger btnIdx,NSInteger selectedIdx) {
        if (btnIdx == 1) {
            SettingsPushModel *item7 = self.data[0][1];
            item7.subTitle = options[selectedIdx];
            if ([MineTool sharedTool].highLatitude != selectedIdx+1) {
                [[MineTool sharedTool] saveHighLatitude:selectedIdx+1];
                [self.table reloadData];
                [[NSNotificationCenter defaultCenter] postNotificationName:PrayTimeAlgorithmChangedNotification object:nil];
            }
        }
    };
    [alert show:NO];
}

- (void)showPrayTimeCalOptions{
    NSArray *options = @[TLString(@"Jafari"),TLString(@"Karachi"),TLString(@"ISNA"),TLString(@"MWL"),TLString(@"Makkah"),TLString(@"Egypt"),TLString(@"Tehran")];
    MyAlertOptionViewV3 *alert = [MyAlertOptionViewV3 viewWithOptions:options selectIdx:[MineTool sharedTool].prayTimeCalMeth];
    [alert addActionWithTitle:TLString(@"Cancel") color:UIColorHex(#334139)];
    [alert addActionWithTitle:TLString(@"Done") color:UIColorHex(#00732F)];
    
    alert.block = ^(NSInteger btnIdx,NSInteger selectedIdx) {
        if (btnIdx == 1) {
            SettingsPushModel *item81 = self.data[0][2];
            item81.subTitle = options[selectedIdx];
            if ([MineTool sharedTool].prayTimeCalMeth != selectedIdx) {
                [[MineTool sharedTool] savePrayTimeCalMeth:selectedIdx];
                [self.table reloadData];
                [[NSNotificationCenter defaultCenter] postNotificationName:PrayTimeAlgorithmChangedNotification object:nil];
            }
        }
    };
    [alert show:NO];
}


- (void)shareApp{
    //分享的标题
    NSString *textToShare = @"iMuslim";
    
    //分享的url
    NSURL *urlToShare = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1402389078?mt=8"];
    //在这里呢 如果想分享图片 就把图片添加进去  文字什么的通上
    NSArray *activityItems = @[textToShare, urlToShare];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    
    //不出现在活动项目
    activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
    [self presentViewController:activityVC animated:YES completion:nil];
    // 分享之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            DDLogInfo(@"completed");
            //分享 成功
        } else  {
            DDLogInfo(@"cancled");
            //分享 取消
        }
    };
}

- (void)onSignupTouched{
    UIViewController *c = [SignupViewController new];
    c.hidesBottomBarWhenPushed = YES;
    [self cw_pushViewController:c];
}

- (void)onLoginTouched{
    UIViewController *c = [LoginController new];
    c.hidesBottomBarWhenPushed = YES;
    [self cw_pushViewController:c];
}

- (void)onPortraitViewTouched{
    UIViewController *c = [MineProfileController new];
    c.hidesBottomBarWhenPushed = YES;
    [self cw_pushViewController:c];
}

#pragma mark - table

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *a = self.data[section];
    return a.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.data.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = [NSString stringWithFormat:@"cell%ld%ld",indexPath.section,indexPath.row];
    SettingsCell *cell = [SettingsCell cellWithTable:tableView identifier:identifier];
    NSArray *a = [self.data objectAtIndex:indexPath.section];
    cell.data = a[indexPath.row];
    if(cell.titleLab.font.pointSize != 15){
        cell.titleLab.font = [UIFont systemFontOfSize:15];
    }
    if (cell.subLab.font.pointSize != 15) {
        cell.subLab.font = [UIFont systemFontOfSize:14];
    }
    if (indexPath.row == a.count -1) {
        cell.isLast = YES;
    }
    else{
        cell.isLast = NO;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [Global cellHeightForStandard:56];
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 12)];
    view.backgroundColor = UIColorHex(#F4F4F4);
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 12;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *a = self.data[indexPath.section];
    SettingsModel *model = a[indexPath.row];
    if (model.targetClass) {
        UIViewController *ctr = [model.targetClass new];
        ctr.hidesBottomBarWhenPushed = YES;
//        [self pushViewController:ctr animated:YES];
        [self cw_pushViewController:ctr];
    }
    else if (model.block){
        model.block();
    }
}



@end
